package com.yonyou.crm.cum.customer.ctrl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.tpub.attachment.entity.AttachmentConstant;
import com.yonyou.crm.tpub.attachment.entity.AttachmentVO;
import com.yonyou.crm.tpub.attachment.rmitf.IAttachmentRmService;

@RestController
@RequestMapping(value = "/sys/upload")
public class UploadCtrl extends OSSClientUtil {

	// 附件最大数量
	private static final int ATTACHMENT_MAX_COUNT = 20;
	
	@Autowired
	private IAttachmentRmService service;

	@RequestMapping(value = "{objType}/{objId}", method = RequestMethod.POST)
	public Object uploadFile(@PathVariable("objType") Integer objType, @PathVariable("objId") Long objId, @RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		
		String fileName = multipartFile.getOriginalFilename();
		if (fileName.length() > 100) {
			throw new CrmMessageException("附件名称不得超过100个字符");
		}
	
		long fileSize = multipartFile.getSize();
		if (fileSize > 10 * 1024 * 1024) {
			throw new CrmMessageException("附件大小不得超过10M");
		}
		
		if (service.getCountByObjId(objType, objId) >= ATTACHMENT_MAX_COUNT) {
			throw new CrmMessageException("附件数量不得超过20个");
		}
		
		String fileType = "";
		String newFileName = "";
		if(fileName.lastIndexOf(".") != -1) {
			String[] fileNames = fileName.split("\\.");
			fileType = fileNames[1];
			newFileName = (fileNames[0] + "_"+new Date().getTime() + "."+fileType);
		}
		else {
			newFileName = fileName;
		}

		// 附件默认文件夹，附件默认路径格式：dir + {objType} + {objId}
		String serverFileName = getWholeFileName(AttachmentConstant.ATTACHMENT_DIR, objType.toString(), objId.toString(), newFileName);
		try {
			uploadFile2OSS(multipartFile.getInputStream(), serverFileName);
		} catch (Exception e) {
			throw new CrmMessageException(e.getMessage());
		}
		
		AttachmentVO vo = new AttachmentVO();
		vo.setObjId(objId);
		vo.setObjType(objType);
		vo.setName(fileName);
		vo.setType(fileType);
		vo.setUrl(super.getUrl(serverFileName));

		return ResponseUtil.getObject(service.save(vo), PCCodeConstant.Success, "上传成功");
	}

	@RequestMapping(value = "uploadMore", method = RequestMethod.POST)
	public Object upLoadFile(@RequestParam("file") MultipartFile[] mFile, HttpServletRequest request, HttpServletResponse response)
			throws CrmMessageException {
		Map<String, Object> res = new HashMap<>();
		// MultipartFile转换file
		for (int i = 0; i < mFile.length; i++) {

			// CommonsMultipartFile cf= (CommonsMultipartFile)mFile[i];
			// DiskFileItem fi = (DiskFileItem)cf.getFileItem();
			// File file = fi.getStoreLocation();
			// request.getServletPath();
			// String fileName = mFile[i].getName();
			// File file = new File("" + fileName);
			// String realPath = "C:\\Users\\Administrator\\Desktop\\附件上传测试";
			// String fileName = System.currentTimeMillis() + ".jpeg";
			// String path = realPath + "/" + fileName;
			// try {
			// mFile[i].transferTo(file);
			// } catch (IllegalStateException e) {
			// // TODO 自动生成的 catch 块
			// e.printStackTrace();
			// } catch (IOException e) {
			// // TODO 自动生成的 catch 块
			// e.printStackTrace();
			// }
			// 上传file，并获取url
			// String md5key = uploadObject2OSS(file);// 上传后的文件MD5数字唯一签名
			// if (file.exists() && file.isFile()) {
			// file.delete();
			// }
			// String url = super.getUrl(fileName);// 获取url地址
			// rmService.save(fileName, url, file);
			// List<Object> list = new ArrayList<>();
			// list.add(url);
			// list.add(fileName);
			// list.add(md5key);
			// res.put("data", list);
		}
		return ResponseUtil.getObject(res, PCCodeConstant.Success, "上传成功");
	}

	@RequestMapping(value = "{objType}/{objId}/{fileName}/{fileId}", method = RequestMethod.DELETE)
	public Object deleteFile(@PathVariable("objType") Integer objType,
			@PathVariable("objId") Long objId,
			@PathVariable("fileName") String fileName,
			@PathVariable("fileId") String fileId, HttpServletRequest request,
			HttpServletResponse response) throws CrmMessageException {
		if (fileName == null || StringUtils.isBlank(fileName)) {
			throw new CrmMessageException(PCCodeConstant.ServerError,
					"文件名称不能为空");
		}
		String wholeFileName = getWholeFileName(AttachmentConstant.ATTACHMENT_DIR,
				objType.toString(), objId.toString(), fileName);
		super.deleteFile(wholeFileName);
		String[] fileIds = new String[] { fileId };
		service.batchDelete(fileIds);
		return ResponseUtil.getObject(PCCodeConstant.Success, "删除成功");
	}

	/**
	 * 相关附件查看
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{objType}/{objId}/", method = RequestMethod.GET)
	public Object queryRelateAttachment(
			@PathVariable("objType") Integer objType,
			@PathVariable("objId") Long objId, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("objType", objType);
		param.put("objId", objId);
		List<AttachmentVO> attachmentList = service.getList(param);
		JSONObject result = new JSONObject();
		result.put("data", attachmentList);
		return ResponseUtil.getObject(result);
	}

	private String getWholeFileName(String... token) {
		return StringUtils.join(token, "/");
	}
}
